#include "asstreamiterator.h"
#include <vector>
#include "M_Code_StyledTextCtrl.h"
#include "globals.h"

ASStreamIterator::ASStreamIterator( M_Code_Editor* cbe, const wxChar* in ) :
  m_Ed( cbe ),
  m_CharPtr( in ),
  m_SavedCharPtr( 0 ),
  m_CurChar( 0 ),
  m_CurLine( 0 ),
  m_FoundBookmark( false ),
  m_FoundBreakpoint( false ) {
}

ASStreamIterator::~ASStreamIterator() {
}

bool ASStreamIterator::hasMoreLines() const {
  return ( *m_CharPtr ) != 0;
}

int ASStreamIterator::getStreamLength() const {
  return static_cast<int>( m_Ed->GetControl()->GetLength() );
}

std::string ASStreamIterator::nextLine( M_Code_unused bool emptyLineWasDeleted ) {
  if( m_Ed && m_CurLine && m_Ed->HasBookmark( m_CurLine ) ) {
    m_FoundBookmark = true;
  }
  if( m_Ed && m_CurLine && m_Ed->HasBreakpoint( m_CurLine ) ) {
    m_FoundBreakpoint = true;
  }
  return readLine();
}

std::string ASStreamIterator::peekNextLine() {
  if( !m_SavedCharPtr ) {
    m_SavedCharPtr = m_CharPtr;
  }
  return readLine();
}

void ASStreamIterator::peekReset() {
  m_CharPtr = m_SavedCharPtr;
  m_SavedCharPtr = 0;
}

std::streamoff ASStreamIterator::tellg() {
  return static_cast<std::streamoff>( m_CurChar );
}

std::string ASStreamIterator::readLine() {
  static std::vector<wxChar> buf;
  buf.clear();
  while( *m_CharPtr != 0 ) {
    if( !IsEOL( *m_CharPtr ) ) {
      buf.push_back( *m_CharPtr );
    }
    ++m_CharPtr;
    ++m_CurChar;
    if( IsEOL( *m_CharPtr ) ) {
      if( *m_CharPtr != *( m_CharPtr + 1 ) && IsEOL( *( m_CharPtr + 1 ) ) ) {
        ++m_CharPtr;
        ++m_CurChar;
      }
      break;
    }
  }
  buf.push_back( 0 );
  ++m_CurLine;
  return static_cast<std::string>( cbU2C( &buf[0] ) );
}
